//
//  PhotoBrowserViewCell.swift
//  LBWeibo
//
//  Created by 李博 on 15/7/4.
//  Copyright © 2015年 libo. All rights reserved.
//

import UIKit
import SDWebImage
import FFAutoLayout

protocol PhotoBrowserViewCellDelegate: NSObjectProtocol {
    
    func photoViewCellDidTapImage();
    //照片视图缩放
    func photoViewDidZooming(scale: CGFloat);
    
    func photoViewDidEndZoom()
}

class PhotoBrowserViewCell: UICollectionViewCell, UIScrollViewDelegate {
    
    weak var photoDelegate: PhotoBrowserViewCellDelegate?
    
    var imageURL: NSURL? {
        didSet {
            resetScrollView()
            //显示菊花
            indicator.startAnimating()
            
            imageView.sd_setImageWithURL(imageURL!, placeholderImage: nil) { (image, error, _, _) -> Void in
                //隐藏菊花
                self.indicator.stopAnimating()
                
                //下载完成后自动设置图片尺寸
                self.imagePosion(image)
            }
            
        }
    }
    
    private func resetScrollView() {
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    
    
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        if scale >= 0.8 {
            // 根据缩放结束后 view 的 frame 调整视图位置
            var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
            if offsetX < 0 {
                offsetX = 0
            }
            
            var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
            if offsetY < 0 {
                offsetY = 0
            }
            //重新设置边距
            scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
            
        }
        //通知代理完成缩放
        photoDelegate?.photoViewDidEndZoom()
        
        
    }
    
    func scrollViewDidZoom(scrollView: UIScrollView) {
        
        let scale = imageView.transform.a
        photoDelegate?.photoViewDidZooming(scale)
    }
    
    
    ///设置位置
    private func imagePosion(image: UIImage) {
        let size = self.displaySize(image)
        
        //判断是否是长图
        if bounds.height < size.height {
            
            imageView.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentSize = size
        }else {
        
            let y = (bounds.size.height - size.height) * 0.5
            imageView.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
        }
        

    }
    
    ///计算图片显示尺寸
    private func displaySize(image: UIImage) -> CGSize {
        let scale = image.size.width / image.size.height
        return CGSize(width: scrollView.bounds.width, height: scrollView.bounds.width / scale)
    }
    
    func clickImage() {
        
        photoDelegate?.photoViewCellDidTapImage()
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        scrollView.frame = UIScreen.mainScreen().bounds
        addSubview(scrollView)
        
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
        
        scrollView.addSubview(imageView)
        
        addSubview(indicator)
        indicator.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: nil)
        
        //设置imageView的手势监听
        let tap = UITapGestureRecognizer(target: self, action: "clickImage")
        imageView.addGestureRecognizer(tap)
        imageView.userInteractionEnabled = true
        
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: -- 懒加载控件 --
    lazy private var scrollView = UIScrollView()
    lazy var imageView = UIImageView()
    lazy private var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    
}
